<!-- frontend/src/components/ContractAuditPanel.vue -->
<template>
  <div class="contract-audit-panel">
    <div class="audit-container">
      <!-- 左侧：代码输入区 -->
      <div class="input-section">
        <div class="section-header">
          <h3>🔒 智能合约代码输入</h3>
          <div class="header-actions">
            <button class="btn secondary" @click="loadExample('vulnerable')">漏洞示例</button>
            <button class="btn secondary" @click="loadExample('safe')">安全示例</button>
            <button class="btn ghost" @click="clearCode">清空</button>
          </div>
        </div>

        <div class="code-editor-wrapper">
          <textarea
            v-model="sourceCode"
            class="code-editor"
            placeholder="请粘贴 Solidity 智能合约源码...

例如:
pragma solidity ^0.8.0;

contract MyContract {
    // 您的合约代码
}"
            spellcheck="false"
          ></textarea>
          <div class="editor-footer">
            <span class="code-stats">{{ codeStats }}</span>
          </div>
        </div>

        <div class="action-bar">
          <button 
            class="btn primary large" 
            :disabled="!canAnalyze || analyzing" 
            @click="analyzeContract"
          >
            <span v-if="!analyzing">🔍 开始安全审计</span>
            <span v-else>⏳ 分析中...</span>
          </button>
        </div>
      </div>

      <!-- 右侧：分析结果区 -->
      <div class="result-section">
        <div class="section-header">
          <h3>📊 审计报告</h3>
          <div class="header-actions" v-if="hasResult">
            <button class="btn ghost" @click="copyReport">📋 复制</button>
            <button class="btn ghost" @click="downloadReport">💾 下载</button>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!hasResult && !analyzing && !error" class="empty-state">
          <div class="empty-icon">🛡️</div>
          <p class="empty-title">等待分析</p>
          <p class="empty-desc">请在左侧输入智能合约代码，然后点击"开始安全审计"</p>
        </div>

        <!-- 加载状态 -->
        <div v-if="analyzing" class="loading-state">
          <div class="loading-spinner"></div>
          <p>正在使用 AI 深度分析合约安全性...</p>
          <p class="loading-hint">这可能需要几秒钟时间</p>
        </div>

        <!-- 错误状态 -->
        <div v-if="error" class="error-state">
          <div class="error-icon">❌</div>
          <p class="error-title">分析失败</p>
          <p class="error-message">{{ error }}</p>
          <button class="btn primary" @click="error = ''">确定</button>
        </div>

        <!-- 结果展示 -->
        <div v-if="hasResult && !analyzing" class="result-content">
          <!-- 摘要卡片 -->

          <!-- 风险统计 -->
          <div class="stats-grid" v-if="auditResult.findings && auditResult.findings.length > 0">
            <div class="stat-card high">
              <div class="stat-number">{{ countBySeverity('High') }}</div>
              <div class="stat-label">🔴 高危</div>
            </div>
            <div class="stat-card medium">
              <div class="stat-number">{{ countBySeverity('Medium') }}</div>
              <div class="stat-label">🟠 中危</div>
            </div>
            <div class="stat-card low">
              <div class="stat-number">{{ countBySeverity('Low') }}</div>
              <div class="stat-label">🟡 低危</div>
            </div>
            <div class="stat-card info">
              <div class="stat-number">{{ countBySeverity('Info') }}</div>
              <div class="stat-label">🔵 信息</div>
            </div>
          </div>

          <!-- 发现项列表 -->
          <div class="findings-section" v-if="auditResult.findings && auditResult.findings.length > 0">
            <h4>🔍 详细发现 ({{ auditResult.findings.length }})</h4>
            <div 
              v-for="(finding, index) in auditResult.findings" 
              :key="index" 
              class="finding-card"
              :class="finding.severity.toLowerCase()"
            >
              <div class="finding-header">
                <span class="severity-badge" :class="finding.severity.toLowerCase()">
                  {{ getSeverityEmoji(finding.severity) }} {{ finding.severity }}
                </span>
                <span class="swc-badge" v-if="finding.swcId">{{ finding.swcId }}</span>
              </div>
              <h5 class="finding-title">{{ index + 1 }}. {{ finding.title }}</h5>
              <p class="finding-desc">{{ finding.description }}</p>
              
              <div class="finding-evidence" v-if="finding.evidence && finding.evidence.lines && finding.evidence.lines.length > 0">
                <strong>📍 证据行号:</strong> {{ finding.evidence.lines.join(', ') }}
              </div>
              
              <div class="finding-recommendation">
                <strong>💡 修复建议:</strong>
                <p>{{ finding.recommendation }}</p>
              </div>
              
              <div class="finding-confidence" v-if="finding.confidence">
                <div class="confidence-bar">
                  <div class="confidence-fill" :style="{ width: (finding.confidence * 100) + '%' }"></div>
                </div>
                <span class="confidence-text">置信度: {{ (finding.confidence * 100).toFixed(0) }}%</span>
              </div>
            </div>
          </div>

          <!-- 无风险提示 -->
          <div v-else class="no-findings">

            
            <!-- 关键信息展示 -->
            <div class="key-info-card" v-if="auditResult.analysis || auditResult.status">
              <h5>审计关键信息</h5>
              <div class="info-item" v-if="auditResult.status">
                <strong>审计状态:</strong> {{ auditResult.status }}
              </div>
              <div class="info-item" v-if="auditResult.summary && auditResult.summary !== auditResult.status">
                <strong>摘要:</strong> {{ auditResult.summary }}
              </div>
              <div class="info-item" v-if="extractVulnType(auditResult.analysis)">
                <strong>漏洞类型:</strong> {{ extractVulnType(auditResult.analysis) }}漏洞
              </div>
              <div class="info-item" v-if="extractCheckedFunctions(auditResult.analysis)">
                <strong>函数定位:</strong> {{ extractCheckedFunctions(auditResult.analysis) }}
              </div>

            </div>
          </div>

          <!-- Markdown完整报告 -->
          <div class="markdown-report">
            <h4>📄 完整报告</h4>
            <div class="markdown-content">
              <MarkdownRenderer :content="auditResult.report_markdown || ''" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { API_BASE_URL } from '@/config/api';
import MarkdownRenderer from '@/components/MarkdownRenderer.vue';

// Props 定义
interface Props {
  testMode?: boolean;
  testData?: any;
}

const props = withDefaults(defineProps<Props>(), {
  testMode: false,
  testData: null
});

interface Finding {
  swcId: string;
  title: string;
  severity: 'High' | 'Medium' | 'Low' | 'Info';
  description: string;
  evidence?: {
    lines: number[];
    snippets: string[];
  };
  recommendation: string;
  confidence?: number;
}

interface AuditResult {
  success: boolean;
  summary: string;
  findings: Finding[];
  report_markdown: string;
  test_mode: boolean;
  timestamp: string;
  status?: string;
  has_vulnerability?: boolean;
  analysis?: string;
}

const sourceCode = ref('');
const analyzing = ref(false);
const auditResult = ref<AuditResult | null>(null);
const error = ref('');

const canAnalyze = computed(() => {
  return sourceCode.value.trim().length >= 10;
});

const hasResult = computed(() => {
  return auditResult.value !== null;
});

const codeStats = computed(() => {
  const lines = sourceCode.value.split('\n').length;
  const chars = sourceCode.value.length;
  return `${lines} 行 | ${chars} 字符`;
});

const countBySeverity = (severity: string): number => {
  if (!auditResult.value?.findings) return 0;
  return auditResult.value.findings.filter(f => f.severity === severity).length;
};

const getSeverityEmoji = (severity: string): string => {
  const emojiMap: Record<string, string> = {
    'High': '🔴',
    'Medium': '🟠',
    'Low': '🟡',
    'Info': '🔵'
  };
  return emojiMap[severity] || '⚪';
};

const formatTime = (timestamp: string): string => {
  try {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN');
  } catch {
    return timestamp;
  }
};

// 从分析文本中提取漏洞类型
const extractVulnType = (analysis: string | undefined): string => {
  if (!analysis) return '';
  
  // 尝试匹配 "Vulnerability type:" 或 "漏洞类型:"
  const patterns = [
    /(?:Vulnerability type|漏洞类型)[:：]\s*([^\n]+)/i,
    /(?:检查类型|检查的漏洞类型)[:：]\s*([^\n]+)/i,
    /inconsistent\s+state/i,
    /状态不一致/i,
    /reentrancy/i,
    /重入/i
  ];
  
  for (const pattern of patterns) {
    const match = analysis.match(pattern);
    if (match) {
      return match[1]?.trim() || match[0]?.trim() || '';
    }
  }
  
  return '';
};

// 从分析文本中提取检查的函数
const extractCheckedFunctions = (analysis: string | undefined): string => {
  if (!analysis) return '';
  
  // 尝试匹配函数名
  // 注意：matchAll 要求正则表达式必须有 g 标志
  const patterns = [
    /(?:Location|位置|函数)[:：]\s*(?:The\s+)?`?(\w+)\s*function`?/gi,
    /function\s+(\w+)\s*\(/g
  ];
  
  const functions: string[] = [];
  for (const pattern of patterns) {
    try {
      const matches = analysis.matchAll(pattern);
      for (const match of matches) {
        if (match[1] && !functions.includes(match[1])) {
          functions.push(match[1]);
        }
      }
    } catch (err) {
      // 如果 matchAll 失败，尝试使用 match 作为后备
      console.warn('matchAll failed, using match as fallback:', err);
      const match = analysis.match(pattern);
      if (match && match[1] && !functions.includes(match[1])) {
        functions.push(match[1]);
      }
    }
  }
  
  return functions.length > 0 ? functions.join(', ') : '';
};

// 从分析文本中提取关键检查点
const extractKeyPoints = (analysis: string | undefined): string[] => {
  if (!analysis) return [];
  
  const points: string[] = [];
  
  // 提取 Security Recommendations 或 安全建议部分的关键点
  const recSection = analysis.match(
    /(?:##\s*Security Recommendations|##\s*安全建议|##\s*安全建议|💡\s*修复建议)[\s\S]*?(?=##|$)/i
  );
  
  if (recSection) {
    const lines = recSection[0].split('\n');
    for (const line of lines) {
      // 匹配列表项（以 -、*、1. 等开头）
      const match = line.match(/^[\s]*[-*•]\s*(.+)$/);
      if (match && match[1].trim().length > 10) {
        points.push(match[1].trim());
        if (points.length >= 3) break; // 最多提取3个关键点
      }
    }
  }
  
  // 如果没找到，尝试提取其他关键信息
  if (points.length === 0) {
    // 提取 Impact Assessment 或 影响评估的关键信息
    const impactMatch = analysis.match(
      /(?:##\s*Impact Assessment|##\s*影响评估)[\s\S]*?(?=##|$)/i
    );
    if (impactMatch) {
      const text = impactMatch[0].substring(0, 200);
      if (text.length > 20) {
        points.push(text.replace(/^##\s*\S+[\s\n]*/, '').trim().substring(0, 100) + '...');
      }
    }
  }
  
  return points;
};

const analyzeContract = async () => {
  if (!canAnalyze.value || analyzing.value) return;

  analyzing.value = true;
  error.value = '';
  auditResult.value = null;

  console.log("\n" + "=".repeat(80));
  console.log("🔵 [前端发送合约审计请求]");
  console.log(`📤 [前端输出] 合约代码长度: ${sourceCode.value.length} 字符`);

  try {
    const response = await fetch(`${API_BASE_URL}/api/contract/analyze`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        source_code: sourceCode.value
      })
    });

    const data = await response.json();
    console.log("📥 [前端接收] 后端返回数据:", data);
    console.log("=".repeat(80) + "\n");

    if (!response.ok || !data.success) {
      throw new Error(data.error || `HTTP ${response.status}`);
    }

    auditResult.value = {
      ...data.data,
      report_markdown: data.data?.report || data.data?.report_markdown || '暂无报告内容',
      summary: data.data?.status || data.data?.summary || '合约安全审计完成',
      status: data.data?.status || '审计完成',
      has_vulnerability: data.data?.has_vulnerability || false,
      timestamp: data.data?.timestamp || new Date().toISOString(),
      analysis: data.data?.analysis || data.data?.report_markdown || ''
    };
  } catch (err: any) {
    error.value = err.message || '分析失败，请稍后重试';
    console.error('Contract analysis error:', err);
  } finally {
    analyzing.value = false;
  }
};

const loadExample = async (type: 'vulnerable' | 'safe') => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/contract/examples`);
    const data = await response.json();
    
    if (data.success && data.examples[type]) {
      sourceCode.value = data.examples[type].code;
      auditResult.value = null;
      error.value = '';
    }
  } catch (err) {
    console.error('Failed to load example:', err);
  }
};

const clearCode = () => {
  sourceCode.value = '';
  auditResult.value = null;
  error.value = '';
};

const copyReport = async () => {
  if (!auditResult.value?.report_markdown) return;
  
  try {
    await navigator.clipboard.writeText(auditResult.value.report_markdown);
    alert('报告已复制到剪贴板！');
  } catch (err) {
    console.error('Failed to copy:', err);
  }
};

const downloadReport = () => {
  if (!auditResult.value?.report_markdown) return;

  const blob = new Blob([auditResult.value.report_markdown], { type: 'text/markdown' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `contract-audit-${new Date().getTime()}.md`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

// 测试模式：监听 testData 变化并更新组件状态
watch(() => props.testData, (newData) => {
  if (props.testMode && newData) {
    if (newData.loading) {
      analyzing.value = true;
      auditResult.value = null;
      error.value = '';
    } else if (newData.success === false) {
      analyzing.value = false;
      error.value = newData.error || '测试错误';
      auditResult.value = null;
    } else {
      analyzing.value = false;
      error.value = '';
      auditResult.value = newData;
    }
  }
}, { immediate: true });
</script>

<style scoped>
.contract-audit-panel {
  height: 100%;
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background: var(--background);
}

.audit-container {
  flex: 1;
  overflow: hidden;
  display: grid;
  grid-template-columns: 45% 55%;
  gap: 16px;
  padding: 16px;
}

.input-section, .result-section {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--card);
  border: 1px solid var(--border);
  border-radius: 8px;
  overflow: hidden;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-bottom: 1px solid var(--border);
  background: var(--muted);
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 700;
}

.header-actions {
  display: flex;
  gap: 6px;
}

.code-editor-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.code-editor {
  flex: 1;
  width: 100%;
  padding: 12px;
  border: none;
  background: var(--background);
  color: var(--foreground);
  font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
  font-size: 12px;
  line-height: 1.5;
  resize: none;
  overflow-y: auto;
}

.code-editor:focus {
  outline: none;
}

.editor-footer {
  padding: 6px 12px;
  border-top: 1px solid var(--border);
  background: var(--muted);
  font-size: 11px;
  color: var(--muted-foreground);
}

.action-bar {
  padding: 12px 16px;
  border-top: 1px solid var(--border);
  display: flex;
  justify-content: center;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: 1px solid var(--border);
  background: var(--card);
  color: var(--foreground);
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.btn:hover:not(:disabled) {
  background: var(--muted);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn.primary {
  background: hsl(221, 83%, 53%);
  color: white;
  border-color: hsl(221, 83%, 53%);
}

.btn.primary:hover:not(:disabled) {
  background: hsl(221, 83%, 45%);
}

.btn.secondary {
  background: var(--secondary);
  color: var(--secondary-foreground);
  font-size: 13px;
  padding: 6px 12px;
}

.btn.ghost {
  background: transparent;
  border-color: transparent;
  font-size: 13px;
  padding: 6px 12px;
}

.btn.large {
  padding: 12px 28px;
  font-size: 15px;
  font-weight: 600;
}

.result-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.empty-state, .loading-state, .error-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 32px;
  text-align: center;
}

.empty-icon, .error-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-title, .error-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 6px;
}

.empty-desc {
  color: var(--muted-foreground);
  font-size: 12px;
  max-width: 280px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--border);
  border-top-color: hsl(221, 83%, 53%);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-hint {
  color: var(--muted-foreground);
  font-size: 12px;
  margin-top: 6px;
}

.error-message {
  color: var(--destructive);
  margin-bottom: 12px;
  font-size: 12px;
}

.summary-card {
  background: var(--muted);
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 16px;
}

.summary-card h4 {
  margin: 0 0 8px 0;
  font-size: 13px;
}

.summary-card p {
  margin: 0 0 8px 0;
  line-height: 1.5;
  font-size: 12px;
}

.meta-info {
  display: flex;
  gap: 12px;
  font-size: 11px;
  color: var(--muted-foreground);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  margin-bottom: 16px;
}

.stat-card {
  background: var(--card);
  border: 2px solid var(--border);
  border-radius: 6px;
  padding: 12px 8px;
  text-align: center;
}

.stat-card.high { border-color: hsl(0, 84%, 60%); }
.stat-card.medium { border-color: hsl(25, 95%, 53%); }
.stat-card.low { border-color: hsl(48, 96%, 53%); }
.stat-card.info { border-color: hsl(217, 91%, 60%); }

.stat-number {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 11px;
  color: var(--muted-foreground);
}

.findings-section {
  margin-bottom: 16px;
}

.findings-section h4 {
  margin: 0 0 12px 0;
  font-size: 13px;
}

.finding-card {
  background: var(--card);
  border: 1px solid var(--border);
  border-left: 3px solid var(--border);
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 10px;
}

.finding-card.high { border-left-color: hsl(0, 84%, 60%); }
.finding-card.medium { border-left-color: hsl(25, 95%, 53%); }
.finding-card.low { border-left-color: hsl(48, 96%, 53%); }
.finding-card.info { border-left-color: hsl(217, 91%, 60%); }

.finding-header {
  display: flex;
  gap: 6px;
  margin-bottom: 6px;
}

.severity-badge, .swc-badge {
  display: inline-block;
  padding: 3px 6px;
  border-radius: 3px;
  font-size: 10px;
  font-weight: 600;
}

.severity-badge.high { background: hsla(0, 84%, 60%, 0.1); color: hsl(0, 84%, 40%); }
.severity-badge.medium { background: hsla(25, 95%, 53%, 0.1); color: hsl(25, 95%, 40%); }
.severity-badge.low { background: hsla(48, 96%, 53%, 0.1); color: hsl(48, 96%, 40%); }
.severity-badge.info { background: hsla(217, 91%, 60%, 0.1); color: hsl(217, 91%, 40%); }

.swc-badge {
  background: var(--muted);
  color: var(--muted-foreground);
}

.finding-title {
  margin: 0 0 6px 0;
  font-size: 13px;
  font-weight: 600;
}

.finding-desc {
  margin: 0 0 10px 0;
  line-height: 1.5;
  color: var(--muted-foreground);
  font-size: 12px;
}

.finding-evidence, .finding-recommendation {
  margin-bottom: 10px;
  font-size: 12px;
}

.finding-recommendation p {
  margin: 4px 0 0 0;
  padding: 6px;
  background: var(--muted);
  border-radius: 3px;
  font-size: 11px;
}

.finding-confidence {
  display: flex;
  align-items: center;
  gap: 10px;
}

.confidence-bar {
  flex: 1;
  height: 6px;
  background: var(--muted);
  border-radius: 3px;
  overflow: hidden;
}

.confidence-fill {
  height: 100%;
  background: hsl(142, 76%, 36%);
  transition: width 0.3s;
}

.confidence-text {
  font-size: 10px;
  color: var(--muted-foreground);
  white-space: nowrap;
}

.no-findings {
  text-align: center;
  padding: 32px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.success-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.hint {
  color: var(--muted-foreground);
  font-size: 12px;
}

.key-info-card {
  margin: 40px auto 0;
  padding: 32px;
  max-width: 600px;
  width: 100%;
  background: linear-gradient(135deg, var(--muted) 0%, var(--card) 100%);
  border: 2px solid var(--border);
  border-radius: 12px;
  text-align: left;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  position: relative;
}

.key-info-card h5 {
  margin: 0 0 24px 0;
  font-size: 22px;
  font-weight: 800;
  color: var(--foreground);
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  position: relative;
}

.key-info-card h5::before {
  content: "📋";
  font-size: 24px;
}

.info-item {
  margin-bottom: 16px;
  font-size: 15px;
  line-height: 1.6;
  color: var(--foreground);
  padding: 12px 16px;
  background: var(--background);
  border-radius: 8px;
  border-left: 4px solid var(--primary);
  transition: all 0.2s ease;
}

.info-item:hover {
  transform: translateX(4px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-item strong {
  color: var(--primary);
  margin-right: 8px;
  font-weight: 600;
}

.key-points-list {
  margin: 8px 0 0 0;
  padding-left: 20px;
  color: var(--muted-foreground);
}

.key-points-list li {
  margin-bottom: 6px;
  line-height: 1.5;
}

.markdown-report {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--border);
}

.markdown-report h4 {
  margin: 0 0 12px 0;
  font-size: 13px;
}

.markdown-content {
  background: var(--muted);
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 12px;
  max-height: 400px;
  overflow-y: auto;
  font-size: 12px;
}
</style>


